import { useRef, useState } from 'react';
import {
  FooterToolbar,
  ProForm,
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormDateTimeRangePicker,
} from '@ant-design/pro-components';
import { Button, message, Space } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import { codegroupDetail, codegroupEdit } from '@/services/batchManage';
import useDetailType from '@/hooks/useDetailType';
import { activitySearch } from '@/services/activity';

import type { ProFormInstance } from '@ant-design/pro-components';

interface IParams {
  type?: string;
  id?: string;
}

import styles from './style.less';

const defaultValues = {
  activityId: '',
  groupId: '',
  groupName: '',
  needActiveCode: 1,
  couponCodeTimeRange: [null, null],
  activeCodeTimeRange: [null, null],
  activeCodePrex: '',
  activeLimitation: 1,
  productId: '',
  productPrice: '',
  contractNo: '',
  groupOwner: '',
  updateUser: '',
  storeIds: '',
};

const SensitizeManageDetail: React.FC = () => {
  const { isAdd, isModify, params } = useDetailType<IParams>();
  const formRef = useRef<ProFormInstance>();
  const [activityDisabeld, setActivityDisabeld] = useState(false);

  // 新增或者编辑  表单内容-初始化
  const getDetail = async () => {
    // 编辑
    if (params.id && isModify) {
      setActivityDisabeld(true);
      const { code, data } = await codegroupDetail({
        id: params.id,
      });
      if (code === 200 && data) {
        return {
          ...data,
          couponCodeTimeRange: [data.couponCodeStartTime, data.couponCodeEndTime],
          activeCodeTimeRange: [data.activeCodeStartTime, data.activeCodeEndTime],
        };
      }
    }
    // 新增直接过来的
    if (params.id && isAdd) {
      setActivityDisabeld(true);
      return { ...defaultValues, activityId: params.id };
    }
    return { ...defaultValues };
  };

  const goToList = () => {
    history.push('/profile/batchManage');
  };

  const restProForm = () => {
    formRef.current?.setFieldsValue({
      ...defaultValues,
      activityId: activityDisabeld ? params.id : '',
    });
  };
  const onValueChange = (value: any) => {
    console.log(value, 'onValueChange');
  };

  const onFinish = async (value: Partial<API.CodegroupEditInfo>) => {
    console.log('onFinish---value', isAdd, isModify, value);
    if (
      Number(value.productPrice) !== 0 &&
      value.productPrice &&
      Number(value.productPrice) % 1 !== 0
    ) {
      message.error('激活码产品金额不能为小数');
      return;
    }

    const response = await activitySearch({
      pageNo: 1,
      pageSize: 10,
      // @ts-ignore
      activityId: value.activityId || '',
    });

    if (
      response.code === 200 &&
      response.data &&
      response.data.rows &&
      response.data.rows.length === 0
    ) {
      message.error('请先把该券转成批次后再次操作');
      return;
    }

    if (
      response.code === 200 &&
      response.data &&
      response.data.rows &&
      response.data.rows[0].needGenAsynFileDesc !== '批次券码'
    ) {
      message.error('请先把该券转成批次后再次操作');
      return;
    }

    const param: API.CodegroupEditInfo = {
      ...value,
    };
    // 编辑
    if (isModify && params.id) {
      param.id = params.id;
    }
    const { data, code } = await codegroupEdit(param);
    if (code === 200 && data) {
      message.success('保存成功');
      goToList();
    }
  };

  return (
    <PageContainer>
      <div className={styles['detail-body']}>
        <>
          <ProForm<Partial<API.CodegroupListItem>>
            formRef={formRef}
            layout="horizontal"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            scrollToFirstError
            onValuesChange={onValueChange}
            onFinish={onFinish}
            //@ts-ignore
            request={getDetail}
            submitter={{
              searchConfig: {
                resetText: '返回',
              },
              render: (_, dom) => (
                <FooterToolbar
                  extra={
                    <div style={{ textAlign: 'center', padding: '5px 0' }}>
                      <Space>
                        <Button type="primary" onClick={restProForm}>
                          重置
                        </Button>
                        <Button onClick={goToList}>返回</Button>
                        {dom[1]}
                      </Space>
                    </div>
                  }
                />
              ),
            }}
          >
            <>
              <ProForm.Group>
                <ProFormText
                  disabled={activityDisabeld}
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="activityId"
                  label="活动id"
                  placeholder="activityId(必填)"
                  rules={[{ required: true, message: '不得为空' }]}
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="groupId"
                  label="批次ID"
                  placeholder="groupId(必填)"
                  rules={[{ required: true, message: '不得为空' }]}
                />
              </ProForm.Group>

              <ProForm.Group>
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="groupName"
                  label="批次名称"
                  placeholder="groupName(必填)"
                  rules={[{ required: true, message: '不得为空' }]}
                />
                <ProFormSelect
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="needActiveCode"
                  label="是否需要激活码"
                  placeholder=""
                  options={[
                    { label: '不需要', value: 0 },
                    { label: '需要', value: 1 },
                  ]}
                />
              </ProForm.Group>
              <ProForm.Group>
                {/* couponCodeStartTime */}
                {/* couponCodeEndTime */}
                <ProFormDateTimeRangePicker
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="couponCodeTimeRange"
                  label="兑换码有效期"
                  fieldProps={{
                    placeholder: ['开始时间', '结束时间'],
                  }}
                  transform={(e) => {
                    return {
                      couponCodeStartTime: e[0] || '',
                      couponCodeEndTime: e[1] || '',
                    };
                  }}
                />
                {/* activeCodeStartTime */}
                {/* activeCodeEndTime */}
                <ProFormDateTimeRangePicker
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="activeCodeTimeRange"
                  label="激活码效期"
                  fieldProps={{
                    placeholder: ['开始时间', '结束时间'],
                  }}
                  transform={(e) => {
                    return {
                      activeCodeStartTime: e[0] || '',
                      activeCodeEndTime: e[1] || '',
                    };
                  }}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="activeCodePrex"
                  label="激活码前缀"
                  placeholder="activeCodePrex"
                  rules={[
                    {
                      validator: (_, value) => {
                        const regex = /^6\d{9}$/;
                        if (value && !regex.test(value)) {
                          return Promise.reject('激活码前缀由数字组成且长度为10，以数字6开头');
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                />
                <ProFormSelect
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="activeLimitation"
                  label="是否激活限制​"
                  placeholder=""
                  options={[
                    { label: '不限制', value: 0 },
                    { label: '限制', value: 1 },
                  ]}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="productId"
                  label="激活码产品Id"
                  placeholder="productId"
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="productPrice"
                  label="激活码产品金额(订单单价)"
                  placeholder="productPrice"
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="contractNo"
                  label="合同编号"
                  placeholder="contractNo"
                />
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="updateUser"
                  label="修改人"
                  placeholder="updateUser"
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="groupOwner"
                  label="申请人"
                  placeholder="groupOwner"
                />
                <ProFormTextArea
                  fieldProps={{ rows: 4 }}
                  labelCol={{ span: 8 }}
                  // width="lg"
                  style={{ width: '100%' }}
                  name="storeIds"
                  label="可激活餐厅号"
                  placeholder="storeIds"
                />
              </ProForm.Group>
            </>
          </ProForm>
        </>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageDetail;
